package com.xiangban.yanglaodajie_platform.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiangban.yanglaodajie_platform.dao.*;
import com.xiangban.yanglaodajie_platform.entity.*;
import com.xiangban.yanglaodajie_platform.entity.dto.*;
import com.xiangban.yanglaodajie_platform.entity.res.ApiResultCode;
import com.xiangban.yanglaodajie_platform.exception.BizException;
import com.xiangban.yanglaodajie_platform.rabbit.CancelOrderSender;
import com.xiangban.yanglaodajie_platform.utils.CommonUtils;
import com.xiangban.yanglaodajie_platform.utils.PageUtil;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.xiangban.yanglaodajie_platform.utils.CommonUtils.*;


/**
 * @Author Mr. MaYaYun
 * @Data 2021/3/24 9:40
 */
@Service
public class OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private PageUtil pageUtil;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CommonUtils commonUtils;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private TakesOrdersMapper takesOrdersMapper;
    @Autowired
    private CancelOrderSender cancelOrderSender;
    @Autowired
    private ordersDeliveryMapper ordersDeliveryMapper;
    @Autowired
    private DeliveryAddressMapper deliveryAddressMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private TakesMapper takesMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AccumulatePointsMapper accumulatePointsMapper;
    @Autowired
    private RefundMapper refundMapper;
    @Autowired
    private RefundGoodsMapper refundGoodsMapper;
    @Autowired
    private ShopLoginMapper shopLoginMapper;
    @Autowired
    private WalletLogMapper walletLogMapper;


    /**
     * 购物车添加到订单里
     * @param shoppingCartDto
     * @return
     */
    @Transactional
    public Object save(ShoppingCartDto shoppingCartDto) throws ParseException {
        Set<Object> objects = checkShopType(shoppingCartDto.getIds());//是否配送 ：去重查is_dispatching
        Object is_dispatching = "";

        if (objects.size()>0){
            //返回 商品店铺类型不统一
            if (objects.size()>1){
                return -2;
            }
            for (Object object : objects) {
                is_dispatching = object;
            }
        }
        shoppingCartDto.setUserId(Integer.parseInt(commonUtils.getUserId(request)));
        List<ShoppingCartDto> shopId = ordersMapper.getShopId(shoppingCartDto);//根据多个商品id查询出商家id哪几个
        ArrayList<Object> list = new ArrayList<>();
        Map<String,Object> res = new HashMap<>();
        ArrayList map2 = new ArrayList();

        if (shopId == null) {
            return -1;
        }
        for (ShoppingCartDto cartDto : shopId) {
            BigDecimal totalPrice = new BigDecimal(0);
            Integer totalNum = 0;
            ShoppingCartDto shoppingCartDto1 = new ShoppingCartDto();
            shoppingCartDto1.setIds(shoppingCartDto.getIds());
            shoppingCartDto1.setUserId(shoppingCartDto.getUserId());
            shoppingCartDto1.setShopId(cartDto.getShopId());

            HashMap<String, Object> map1 = new LinkedHashMap<>();
//            map1.put("shopName",cartDto.getShopName());
            String code = RandomStringUtils.randomNumeric(8);
            String orderNumber = new SimpleDateFormat("yy-MM-dd-HH-mm-ss").format(new Date()).replace("-", "") + code;
            map1.put("shopId", cartDto.getShopId());
            map1.put("orderNumber", orderNumber);
            map1.put("userId", shoppingCartDto.getUserId());
            map1.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            ArrayList<Map<String, Object>> maps = new ArrayList<>();

            List<ShoppingCartDto> goods = ordersMapper.findGoods(shoppingCartDto1);//根据user_id、shop_id和多个good_id查询出模板Orders信息


            //商家商品
            for (ShoppingCartDto good : goods) {
                if (good.getShopStatus().equals("1") || good.getShopStatus().equals("0")){
                    if (good.getGoodStatus().equals("1")){
                        HashMap<String, Object> map = new HashMap<>();
                        if (good.getNumber() <= good.getInventory()) {//购物车数量小于或等于库存量
                            map.put("goodsId", good.getGoodsId());
                            map.put("goodsName", good.getGoodsName());
                            map.put("number", good.getNumber());
                            map.put("verificationStatus",0);//0：未核销，1：已完成核销 2:退款
                            map.put("goodsPrice", new BigDecimal(good.getGoodsPrice()).multiply(new BigDecimal(good.getNumber())));
                            BigDecimal goodsPrice = new BigDecimal(map.get("goodsPrice").toString());
                            int number = Integer.parseInt(map.get("number").toString());
                            totalNum += number;
                            totalPrice = totalPrice.add(goodsPrice);
                            goodsMapper.updateById(good);
                            maps.add(map);
                        }else {
                            return -5;
                        }
                    }else {
                        return -4;
                    }
                }else {
                    return -6;
                }
            }
            map1.put("number", totalNum);
            map1.put("goodsPrice", totalPrice);
            map1.put("goodSku", JSON.toJSONString(maps));
            map1.put("orderStatus", -1);
            map1.put("isTakes", shoppingCartDto.getIsDispatching());//是否配送,值是null的话不是配送商家也不是配送商品
            ObjectMapper mapper = new ObjectMapper();
            if (map1.get("isTakes") != null &&map1.get("isTakes").equals(1)){
                map1.put("takesState",1);
            }else if (map1.get("isTakes") != null &&map1.get("isTakes").equals(2)){
                map1.put("takesState",-1);
            }
            Orders orders1 = mapper.convertValue(map1, Orders.class);
            ordersMapper.insert(orders1);
            if (map1.get("isTakes").equals(2)){
                TakesOrders takesOrders = new TakesOrders();
                takesOrders.setOrderNumber(map1.get("orderNumber").toString());
                takesOrders.setUserId(shoppingCartDto.getUserId());
                takesOrders.setTakesTime(shoppingCartDto.getTakesTime());
                takesOrders.setTakesPhone(shoppingCartDto.getTakesPhone());
                takesOrdersMapper.insert(takesOrders);
                //设置超时确认自提
                String takesTime = shoppingCartDto.getTakesTime();
                Date parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(takesTime);
                long time = parse.getTime();//自取时间
                long time1 = new Date().getTime();//今天时间
                long time2 = time - time1;
                cancelOrderSender.sendMessages(orderNumber,time2);
            }else if (map1.get("isTakes").equals(1)){
                if (BizEmpty(shoppingCartDto.getAddressId())){
                    return -3;
                }
                ordersDelivery ordersDelivery = new ordersDelivery();
                ordersDelivery.setOrderNumber(map1.get("orderNumber").toString());
                ordersDelivery.setAddressId(shoppingCartDto.getAddressId());
                ordersDelivery.setCreateTime(new Date());
                ordersDeliveryMapper.saveOrdersAddress(ordersDelivery);
                //设置超时确认收货
                cancelOrderSender.sendMessages(orderNumber,OVER_TIME);
            }
            map2.add(map1.get("orderNumber"));
            res.put("orderNumber",map2);
            res.put("is_dispatching",is_dispatching);
            cancelOrderSender.sendMessage(orderNumber,DELAY_TIME);


        }
        shoppingCartMapper.delShoppingCart(shoppingCartDto);
        return res;
    }

    /**
     * 获取所有订单
     *
     * @param orders
     * @return
     */
    public PageInfo<OrdersDto> getList(Orders orders) {
        orders.setUserId(Integer.parseInt(commonUtils.getUserId(request)));
        PageHelper.startPage(pageUtil.getPage().getPageNum(), pageUtil.getPage().getPageSize());
        List<OrdersDto> order = ordersMapper.findOrders(orders);
        for (OrdersDto ordersDto : order) {
            String goodSku = ordersDto.getGoodSku();
            JSONArray objects = JSON.parseArray(goodSku);//字符串转对象
            ordersDto.setGoodSkuDto(objects);
            ordersDto.setGoodSku(null);
        }
        return new PageInfo<>(order);
    }

        /**
     * 修改订单配送状态
     * @param orderNoDto
     * @return
     */
    public void updateIsAfhalen(OrderNoDto orderNoDto) {
        orderNoDto.setUserId(Integer.parseInt(commonUtils.getUserId(request)));
        if (BizEmpty(orderNoDto.getOrderStatus())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        ordersMapper.updateStatus(orderNoDto);
    }

    /**
     * 删除订单
     * @param orders
     * @return
     */
    public void deleteOrder(Orders orders) {
        if (BizEmpty(orders.getOrderNumber())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        ordersMapper.deleteOrder(orders);
    }

    /**
     * 修改订单配送状态 商家
     * @param orders
     * @return
     */
    public void updateStatus(Orders orders) {//参数：商家id、订单状态、如果是配送订单要有配送状态
        orders.setShopId(Integer.parseInt(commonUtils.getShopId(request)));
        if (BizEmpty(orders.getOrderNumber())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(orders.getTakesState())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        ordersMapper.updateShopOrdersStatus(orders);
    }


    public Set<Object> checkShopType (List<Integer> goodsIds) {
        List<Map<String, String>> checkShopType = goodsMapper.checkShopType(goodsIds);
        HashSet<Object> set = new HashSet<>();
        for (Map<String, String> stringStringMap : checkShopType) {
            Object is_dispatching = stringStringMap.get("is_dispatching");
            set.add(is_dispatching);
        }
        return set;
    }


    public OrdersDto getOrdersInfo(Orders orders) {//参数：订单编号
        String userId = commonUtils.getUserId(request);
        orders.setUserId(Integer.parseInt(userId));
        if (BizEmpty(orders.getOrderNumber())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }

        OrdersDto ordersDto = ordersMapper.orderInfoByOderNo(orders);//订单信息
        String goodSku = ordersDto.getGoodSku();
        JSONArray objects = JSON.parseArray(goodSku);
        ObjectMapper objectMapper = new ObjectMapper();
        ArrayList<Object> list = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            Object o = objects.get(i);
            Map map = objectMapper.convertValue(o, Map.class);
            int goodsId = (int) map.get("goodsId");
            Goods info = goodsMapper.findInfo(goodsId);
            map.put("image",info.getLogo());
            list.add(map);
        }
        ordersDto.setGoodSkuDto(list);
        ordersDto.setGoodSku(null);//用不到了设置为空

        Shop shopByShopId = shopMapper.findShopByShopId(ordersDto.getShopId());//查询商家名字
        ordersDto.setShopName(shopByShopId.getShopName());

        if (ordersDto.getIsTakes()==1){
            ordersDelivery ordersDelivery = new ordersDelivery();
            ordersDelivery.setOrderNumber(orders.getOrderNumber());
            ordersDelivery addressByOrderNumber = ordersDeliveryMapper.findAddressByOrderNumber(ordersDelivery);//查询订单配送地址

            DeliveryAddress deliveryAddress = new DeliveryAddress();
            deliveryAddress.setId(addressByOrderNumber.getAddressId());
            deliveryAddress.setUserId(orders.getUserId());
            DeliveryAddressDto object = deliveryAddressMapper.findObject(deliveryAddress);//查询地址
                if (object!= null){
                    ordersDto.setName(object.getName());
                    ordersDto.setPhone(object.getPhone());
                    ordersDto.setProvince(object.getProvince());
                    ordersDto.setCity(object.getCity());
                    ordersDto.setDistrict(object.getDistrict());
                    ordersDto.setAddress(object.getAddress());
                }
        }
        else if (ordersDto.getIsTakes()== 2){
            Integer shopId = ordersDto.getShopId();
            ShopDto dto = new ShopDto();
            dto.setShopId(shopId);
            List<ShopDto> regionCity = shopMapper.getRegionCity(dto);

            TakesOrders takesOrders = new TakesOrders();
            takesOrders.setOrderNumber(orders.getOrderNumber());
            TakesOrders takesOrders1 = takesMapper.findTakesOrders(takesOrders);
            for (ShopDto shopDto : regionCity) {
                ordersDto.setPhone(takesOrders1.getTakesPhone());
                ordersDto.setProvince(shopDto.getProvince());
                ordersDto.setCity(shopDto.getCity());
                ordersDto.setDistrict(shopDto.getDistrict());
                ordersDto.setAddress(shopDto.getAddress());
            }
            ordersDto.setLongitude(shopByShopId.getLongitude());
            ordersDto.setLatitude(shopByShopId.getLatitude());
        }
        else if (ordersDto.getIsTakes()== -1){
            Integer shopId = ordersDto.getShopId();
            ShopDto dto = new ShopDto();
            dto.setShopId(shopId);
            List<ShopDto> regionCity = shopMapper.getRegionCity(dto);

            for (ShopDto shopDto : regionCity) {
                ordersDto.setShopLogo(shopDto.getShopLogo());
                ordersDto.setPhone(shopDto.getPhone());
                ordersDto.setProvince(shopDto.getProvince());
                ordersDto.setCity(shopDto.getCity());
                ordersDto.setDistrict(shopDto.getDistrict());
                ordersDto.setAddress(shopDto.getAddress());
            }
            ordersDto.setLongitude(shopByShopId.getLongitude());
            ordersDto.setLatitude(shopByShopId.getLatitude());
        }

        return ordersDto;
    }

    public OrdersDto getShopOrdersInfo(Orders orders) {//参数：订单编号 、商家id
        if (commonUtils.getShopId(request) == null){
            throw new BizException(ApiResultCode.FAILED_TOKEN);
        }

        orders.setShopId(Integer.parseInt(commonUtils.getShopId(request)));
        if (BizEmpty(orders.getOrderNumber())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }

        OrdersDto ordersDto = ordersMapper.shopOrderInfoByOderNo(orders);//订单信息
        if (ordersDto == null){
            throw  new BizException(ApiResultCode.ORDERS_FALSE);
        }
        orders.setUserId(ordersDto.getUserId());
        String goodSku = ordersDto.getGoodSku();
        JSONArray objects = JSON.parseArray(goodSku);
        ObjectMapper objectMapper = new ObjectMapper();
        ArrayList<Object> list = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            Object o = objects.get(i);
            Map map = objectMapper.convertValue(o, Map.class);
            int goodsId = (int) map.get("goodsId");
            Goods info = goodsMapper.findInfo(goodsId);
            map.put("image",info.getLogo());
            list.add(map);
        }
        ordersDto.setGoodSkuDto(list);
        ordersDto.setGoodSku(null);//用不到了设置为空

        Shop shopByShopId = shopMapper.findShopByShopId(ordersDto.getShopId());//查询商家名字
        ordersDto.setShopName(shopByShopId.getShopName());

        if (ordersDto.getIsTakes().equals(1)){
            ordersDelivery ordersDelivery = new ordersDelivery();
            ordersDelivery.setOrderNumber(orders.getOrderNumber());
            ordersDelivery addressByOrderNumber = ordersDeliveryMapper.findAddressByOrderNumber(ordersDelivery);//查询订单配送地址

            DeliveryAddress deliveryAddress = new DeliveryAddress();
            deliveryAddress.setId(addressByOrderNumber.getAddressId());
            deliveryAddress.setUserId(orders.getUserId());
            DeliveryAddressDto object = deliveryAddressMapper.findObject(deliveryAddress);//查询地址
            if (object!= null){
                ordersDto.setName(object.getName());
                ordersDto.setPhone(object.getPhone());
                ordersDto.setProvince(object.getProvince());
                ordersDto.setCity(object.getCity());
                ordersDto.setDistrict(object.getDistrict());
                ordersDto.setAddress(object.getAddress());
            }
        }
        else if (ordersDto.getIsTakes().equals(2)){
            Integer shopId = ordersDto.getShopId();
            ShopDto dto = new ShopDto();
            dto.setShopId(shopId);
            int date = DateToNumber(getNowTime());
            dto.setDateTime(date);
            List<ShopDto> regionCity = shopMapper.getRegionCity(dto);//查询商家信息

            TakesOrders takesOrders = new TakesOrders();
            takesOrders.setOrderNumber(orders.getOrderNumber());
            TakesOrders takesOrders1 = takesMapper.findTakesOrders(takesOrders);//查询用户自取信息
            UserDto userDto = new UserDto();
            userDto.setUserId(takesOrders1.getUserId());
            UserDto userInfoById = userMapper.getUserInfoById(userDto);//查询用户
            for (ShopDto shopDto : regionCity) {
                ordersDto.setPhone(takesOrders1.getTakesPhone());
                ordersDto.setProvince(shopDto.getProvince());
                ordersDto.setCity(shopDto.getCity());
                ordersDto.setDistrict(shopDto.getDistrict());
                ordersDto.setAddress(shopDto.getAddress());
            }
            ordersDto.setLongitude(shopByShopId.getLongitude());
            ordersDto.setLatitude(shopByShopId.getLatitude());
            ordersDto.setTakesDateTime(takesOrders1.getTakesTime());
            ordersDto.setName(userInfoById.getNickName());
        }
        else if (ordersDto.getIsTakes().equals(-1)){
            Integer shopId = ordersDto.getShopId();
            ShopDto dto = new ShopDto();
            dto.setShopId(shopId);
            List<ShopDto> regionCity = shopMapper.getRegionCity(dto);//查询商家信息

            for (ShopDto shopDto : regionCity) {
                ordersDto.setShopLogo(shopDto.getShopLogo());
                ordersDto.setProvince(shopDto.getProvince());
                ordersDto.setCity(shopDto.getCity());
                ordersDto.setDistrict(shopDto.getDistrict());
                ordersDto.setAddress(shopDto.getAddress());
            }
            ordersDto.setLongitude(shopByShopId.getLongitude());
            ordersDto.setLatitude(shopByShopId.getLatitude());

            UserDto userDto = new UserDto();
            userDto.setUserId(ordersDto.getUserId());
            UserDto userInfoById = userMapper.getUserInfoById(userDto);

            ordersDto.setName(userInfoById.getNickName());
            ordersDto.setPhone(userInfoById.getPhone());
        }

        return ordersDto;
    }


    public Map<String,Object> todayIntegral(Orders orders) {//参数：商家id、查询的时间
        if(BizEmpty(commonUtils.getShopId(request))){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        orders.setShopId(Integer.parseInt(commonUtils.getShopId(request)));
        HashMap<String, Object> map = new HashMap<>();
        orders.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()).replace("-", ""));

        OrdersDto todayIntegral = ordersMapper.findTodayIntegral(orders);//今日营业额
        if (todayIntegral == null){
            map.put("todayIntegral",0);
        }else {
            map.put("todayIntegral",todayIntegral.getSumGoodsPrice());
        }
        OrdersDto ordersNumber = ordersMapper.findOrdersNumber(orders);//今日订单数量
        if (ordersNumber == null){
            map.put("todayOrdersNumber",0);
        }else {
            map.put("todayOrdersNumber",ordersNumber.getSumOrdersNumber());
        }
        OrdersDto allOrderPrice = ordersMapper.findAllOrderPrice(orders);//总收入(积分)
        if (allOrderPrice == null){
            map.put("allOrderPrice",0);
        }else {
            map.put("allOrderPrice",allOrderPrice.getAllSumGoodsPrice());
        }
        return map;
    }

//    public int todayOrdersNumber(Orders orders) {//参数：商家id、查询的时间
//        if (BizEmpty(orders.getUpdateTime())){
//            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
//        }
//        orders.setShopId(Integer.parseInt(commonUtils.getShopId(request)));
//        orders.getUpdateTime().replace("-","");
//        OrdersDto ordersNumber = ordersMapper.findOrdersNumber(orders);
//        return ordersNumber.getSumOrdersNumber();
//    }
//
//    public int allIntegral(Orders orders) {//参数：商家id
//        orders.setShopId(Integer.parseInt(commonUtils.getShopId(request)));
//        OrdersDto allOrderPrice = ordersMapper.findAllOrderPrice(orders);
//        return allOrderPrice.getAllSumGoodsPrice();
//    }
    @Transactional
    public void Refund(RefundDto refund) {//参数：订单编号、申请理由、申请图片(可选)
        if (BizEmpty(commonUtils.getUserId(request))){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(refund.getOrderNumber())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(refund.getRefundRemark())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(refund.getRefundType())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(refund.getRefundCause())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(refund.getGoodsId())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        refund.setUserId(Integer.parseInt(commonUtils.getUserId(request)));
        Orders orders = new Orders();
        orders.setOrderNumber(refund.getOrderNumber());
        orders.setUserId(refund.getUserId());
        OrdersDto ordersDto = ordersMapper.selectOrderInfo(orders);//退款订单
        if (ordersDto != null){
            if (ordersDto.getOrderStatus().equals("1")){
                refund.setRefundStatus(-1);
                refund.setType(1);
                refundMapper.saveRefund(refund);
                for (int i = 0; i < refund.getGoodsId().size(); i++) {
                    RefundGoods refundGoods = new RefundGoods();
                    refundGoods.setGoodsId(refund.getGoodsId().get(i));
                    refundGoods.setRefundId(refund.getId());
                    refundGoodsMapper.insertRefundGoods(refundGoods);
                }


                HashMap<String, Object> map = new HashMap<>();
                map.put("order_status",-3);
                map.put("order_number",refund.getOrderNumber());
                ordersMapper.updOrderStatus(map);
            }else {
                throw new BizException(ApiResultCode.ORDERS_ERROR);
            }
        }else {
            throw new BizException(ApiResultCode.ORDERS_NULL);
        }

    }

    /**
     *  参数：订单编号、用户id
     * @param refund
     * @return 退款详情（商家）（用户）
     */
    public Object refundInfo(RefundDto refund){
        if (BizEmpty(refund.getOrderNumber())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        RefundDto refundDto = refundMapper.selectRefundInfo(refund);//查询出退款表信息
        if (refundDto != null){

                String refundImage = refundDto.getRefundImage();
                if (refundImage != null) {
                    JSONArray objects = JSON.parseArray(refundImage);
                    refundDto.setRefundImages(objects);
                    refundDto.setRefundImage(null);
                }
                if (refundDto.getShopImage() != null) {
                    String shopImage = refundDto.getShopImage();
                    JSONArray objects1 = JSON.parseArray(shopImage);
                    refundDto.setShopImages(objects1);
                    refundDto.setShopImage(null);
                }
                HashMap<String, Object> map = new HashMap<>();
                ArrayList<Object> list = new ArrayList<>();
                ArrayList<Object> list1 = new ArrayList<>();
                //退款商品图     TODO
                List<RefundGoods> refundGoods = refundGoodsMapper.selectRefundGoodsList(refundDto.getId());
                for (int j = 0; j < refundGoods.size(); j++) {
                    list.add(refundGoods.get(j).getGoodsId());
                }
                map.put("list", list);
                List<GoodsDto> goods = goodsMapper.selectGoodsList(map);

            ArrayList<GoodsDto> list2 = new ArrayList<>();

            for (int i = 0; i < goods.size(); i++) {
                    Integer goodsId = goods.get(i).getGoodsId();

                    Orders orders = new Orders();
                orders.setOrderNumber(refund.getOrderNumber());
                Orders orders1 = ordersMapper.selectOrder(orders);
                String goodSku = orders1.getGoodSku();
                JSONArray objects = JSON.parseArray(goodSku);
                ObjectMapper objectMapper = new ObjectMapper();
                for (int j = 0; j < objects.size(); j++) {
                Object o = objects.get(j);
                Map map1 = objectMapper.convertValue(o, Map.class);
                int goodsid = (int) map1.get("goodsId");
                int number = (int) map1.get("number");
                    if (goodsId == goodsid) {
                        goods.get(i).setNumber(number);
                        list2.add(goods.get(i));
                        break;
                    }
                }

            }
            refundDto.setRefundGoods(list2);
            return refundDto;
        }else {
            RefundDto refundDto1 = new RefundDto();
            return refundDto1;
        }
    }

    @Transactional
    public void isRefund(RefundDto refundDto) {//参数：订单编号、是否退款(1、同意，2：拒绝)、理由描述、描述图
        if (BizEmpty(refundDto.getRefundStatus())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(refundDto.getRefundId())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }

        HashMap<String, Object> map2 = new HashMap<>();
        ArrayList<Object> list = new ArrayList<>();

        Integer refundId = refundDto.getRefundId();//退款记录id

        Orders orders1 = refundMapper.selectRefundInfoByInteger(refundId);
        refundDto.setOrderNumber(orders1.getOrderNumber());


        if (refundDto.getRefundStatus() == 1){

            List<RefundGoods> refundGoods = refundGoodsMapper.selectRefundGoodsList(refundId);//查询退款商品id
            for (RefundGoods refundGood : refundGoods) {
                list.add(refundGood.getGoodsId());
            }
            map2.put("list",list);

            List<GoodsDto> goods = goodsMapper.selectGoodsList(map2);
            for (int i = 0; i < goods.size(); i++) {


                Orders orders = refundMapper.selectRefundInfoByInteger(refundId);//查询出退款订单
                refundDto.setOrderNumber(orders.getOrderNumber());

                Integer goodsId = goods.get(i).getGoodsId();
                BigDecimal price = goods.get(i).getPrice();
                HashMap<String, Object> map = new HashMap<>();
                map.put("integral",price);
                map.put("userId",orders.getUserId());
                userMapper.updateAccumulatePoints(map);//增加用户退款积分

                AccumulatePoints accumulatePoints = new AccumulatePoints();
                accumulatePoints.setOrderNumber(refundDto.getOrderNumber());
                accumulatePoints.setUserId(orders.getUserId());
                accumulatePoints.setType(1);
                accumulatePoints.setAccumulatePoints(price);
                accumulatePoints.setPayState(0);
                accumulatePoints.setDescribe("退款");
                accumulatePoints.setRecodeType(5);
                accumulatePointsMapper.saveAP(accumulatePoints);//增加积分记录

                //商家帐户扣除积分  TODO
                ShopLogin shopLogin = new ShopLogin();
                shopLogin.setWallet(price);
                shopLogin.setShopId(orders.getShopId());
                shopLoginMapper.updWallet(shopLogin);

                //钱包日志记录  TODO
                WalletLog walletLog = new WalletLog();
                walletLog.setMoney(price);
                walletLog.setType(2);
                walletLog.setShopId(orders.getShopId());
                walletLog.setOrderNumber(refundDto.getOrderNumber());
                walletLog.setDescribe("退款");
                walletLog.setRecodeType(2);
                walletLogMapper.insertWalletLog(walletLog);


                String goodSku = orders.getGoodSku();
                JSONArray objects = JSON.parseArray(goodSku);
                ObjectMapper objectMapper = new ObjectMapper();
                int a = 0;
                for (int j = 0; j < objects.size(); j++) {
                    Object o = objects.get(j);
                    Map map1 = objectMapper.convertValue(o, Map.class);
                    int goodsid = (int) map1.get("goodsId");
                    int verificationStatus = (int)map1.get("verificationStatus");
                    if (verificationStatus == 0) {
                        if (goodsId == goodsid) {
                            HashMap<String, Object> map3 = new HashMap<>();
                            int number = (int) map1.get("number");
                            map3.put("goodsId", goodsId);
                            map3.put("number", number);
                            goodsMapper.updateInventory(map3);//增加退款库存

                            map1.put("verificationStatus", 2);
                            objects.set(j, map1);
                            ordersMapper.updateSku(JSON.toJSONString(objects), orders.getOrderNumber());
                        }
                    }else if (verificationStatus == 1 || verificationStatus == 2) {
                        a++;
                    } else {
                        throw new BizException(ApiResultCode.GOODS_EXIT);
                    }
                }
                if (a == objects.size()-1){
                    HashMap<String, Object> map1 = new HashMap<>();
                    map1.put("order_status",-4);
                    map1.put("order_number",orders.getOrderNumber());
                    ordersMapper.updOrderStatus(map1);//修改订单已退款状态
                }else {
                    HashMap<String, Object> map1 = new HashMap<>();
                    map1.put("order_status",1);
                    map1.put("order_number",orders.getOrderNumber());
                    ordersMapper.updOrderStatus(map1);
                }
            }
            refundMapper.updateRefund(refundDto);//更改退款表订单内容

        }else{
            HashMap<String, Object> map1 = new HashMap<>();
            map1.put("order_status",1);
            map1.put("order_number",refundDto.getOrderNumber());
            ordersMapper.updOrderStatus(map1);
            refundMapper.updateRefund(refundDto);//更改退款表订单内容
        }
    }

    public Object orderInfoByOrderNumber(Map<String, Object> map) {//参数：订单编号
        if (BizEmpty(map.get("orderNumber"))){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        int shopId = Integer.parseInt(commonUtils.getShopId(request));
        Object orderNumber = map.get("orderNumber");
        Orders orders = new Orders();
        orders.setOrderNumber(orderNumber.toString());
        OrdersDto ordersDto = ordersMapper.orderInfoByOderNo(orders);//订单详情

        if (ordersDto == null){
            throw new BizException(ApiResultCode.ORDERS_NULL);
        }
        if (shopId != ordersDto.getShopId()){
            throw new BizException(ApiResultCode.ORDERS_FALSE);
        }
        if (ordersDto.getOrderStatus().equals("-1")){
            throw new BizException(ApiResultCode.ORDERS_EXCEPTION);
        }
        if (ordersDto.getOrderStatus().equals("2")){
            throw new BizException(ApiResultCode.ORDERS_TRUE);
        }
        String goodSku = ordersDto.getGoodSku();
        JSONArray objects = JSON.parseArray(goodSku);
        ObjectMapper objectMapper = new ObjectMapper();
        ArrayList<Object> list = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            Object o = objects.get(i);
            Map map1 = objectMapper.convertValue(o, Map.class);
            int goodsId = (int) map1.get("goodsId");
            Goods info = goodsMapper.findInfo(goodsId);
            map1.put("image",info.getLogo());
            list.add(map1);
        }
        ordersDto.setGoodSkuDto(list);
        ordersDto.setGoodSku(null);
        return ordersDto;


    }

    public void destroyOrder(OrderNoDto orderNoDto) {
        if (BizEmpty(orderNoDto.getOrderNumber())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(orderNoDto.getGoodsIds())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }

        String orderNumber = orderNoDto.getOrderNumber();
        List<Integer> goodsIds = orderNoDto.getGoodsIds();
        for (Integer goodsId : goodsIds) {
            Orders orders = new Orders();
            orders.setOrderNumber(orderNumber);
            OrdersDto ordersDto = ordersMapper.orderInfoByOderNo(orders);
            if (ordersDto.getOrderStatus().equals("1")){
                String goodSku = ordersDto.getGoodSku();
                JSONArray objects = JSON.parseArray(goodSku);
                ObjectMapper objectMapper = new ObjectMapper();
                int a = 0;
                Set<Integer> set = new HashSet<>();
                for (int i = 0; i < objects.size(); i++) {
                    Object o = objects.get(i);
                    Map map1 = objectMapper.convertValue(o, Map.class);
                    int Id = (int) map1.get("goodsId");
                    int verificationStatus = (int) map1.get("verificationStatus");
                    set.add(Id);
                    if (verificationStatus == 0 ){
                        if (goodsId == Id){
                            map1.put("verificationStatus",1);
                        }
                    }else {
                        a++;
                    }
                    objects.set(i,map1);//根据索引更改values
                }
                if (!set.contains(goodsId)){//判断传来的goodsId是否存在订单SKU里
                    throw new BizException(ApiResultCode.ORDERS_EXCEPTION);
                }
                if (a == objects.size()-1){
                    ordersMapper.updStatus(orderNoDto);
                }
//                else {
//                    throw new BizException(ApiResultCode.ORDERS_TRUE);
//                }
                ordersMapper.updateSku(JSON.toJSONString(objects),orderNoDto.getOrderNumber());
            }
        }

    }




    public String getNowTime() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        return simpleDateFormat.format(date);
    }

    public int DateToNumber(String date) {
        String[] replace = date.split(":");
        return (Integer.parseInt(replace[0])) * 60 + Integer.parseInt(replace[1]);
    }
}
